<?php
/*
 *      db.class.php
 *
 *      Copyright 2010 Patrice Ferlet <metal3d@gmail.com>
 *
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *      MA 02110-1301, USA.
 */

// $Id: db.class.php 19 2010-12-14 22:46:23Z Metal3d $
// $HeadURL: http://valaya.googlecode.com/svn/trunk/utils/db.class.php $

/**
 *  This class extends PDO and some methods to ease data work
 * */
class DB extends PDO{
	static $instances = array();
	static $datadict = null;

	private $handle = null;
	private $connectionString = "";

	/**
	 * Execute query and returns a Statement
	 *
	 * @param string $sql
	 * @param array $params
	 * @return Statement $statement
	 * */
	public function query($sql,$params=array()) {
		//$this->beginTransaction();
		try {
			$stmt = $this->prepare($sql);
		} catch (Exception $e) {
			die ($e->getMessage());
		}

		Log::write('DB',$stmt->queryString,Log::INFO);

		if ($stmt) $stmt->execute($params);
		else die ($stmt->errorInfo());
		//$this->commit();
		return $stmt;
	}

	/**
	 * Multiton pattern, return instance by name
	 *
	 * @param string $name
	 * @return Db $instance
	 * */
	public function getInstance ($name='default') {
		self::checkDataDict();
		if(!isset(self::$instances[$name])) {

			$conn = _config($name,"db");
			if (is_null($conn)) {
				throw new Exception("You must set db configuration for $name :: Config::getInstance()->set('$name',array('user'=>'','password'=>'',connection=>'mysql:...'),'db')");
			}
			if (!isset($conn['user'])) $conn['user'] = null;
			if (!isset($conn['password'])) $conn['password'] = null;

			self::$instances[$name] = new self($conn['connection'], $conn['user'], $conn['password']);
			self::$instances[$name]->setAttribute(PDO::ATTR_STATEMENT_CLASS, array( 'Statement', array(self::$instances[$name] )) );
		}
		return self::$instances[$name];
	}

	/**
	 * Parse data dictonnaries on modules to get the whole definition
	 *
	 * */
	private function checkDataDict(){
		if(!is_null(self::$datadict)) return;

		$dictfile = _config('var','project').'/cache/datastruct.dict';
		if(file_exists($dictfile)) {
			self::$datadict = unserialize(file_get_contents($dictfile));
			return;
		}

		$modulepath = _config('modulepath','project');
		$dict = glob($modulepath.'*/*.dict.ini');
		self::$datadict = array();
		foreach ($dict as $datadict) {
			self::$datadict = array_merge(self::$datadict, parse_ini_file($datadict,true));
			//TODO :: Set cache
		}
		file_put_contents($dictfile,serialize(self::$datadict));

	}

}
